<template>
  <view class="content">
    <view class="upload-wrapper">
      <!-- 上传按钮 -->
      <view class="upload-btn-container" @tap="chooseFile">
        <up-icon name="folder" size="22" color="#666"></up-icon>
      </view>

      <!-- 上传进度条 -->
      <view class="progress-container" v-if="isUploading">
        <view class="progress-bar">
          <view class="progress-fill" :style="{ width: uploadProgress + '%' }"></view>
        </view>
        <text class="progress-text">{{ uploadProgress }}%</text>
      </view>
    </view>


    <xe-upload ref="XeUpload" :options="uploadOptions" @beforUpload="beforUpload"
      @callback="handleUploadCallback"></xe-upload>
  </view>
</template>

<script>
import { COMMON_API_BASE_URL } from '@/utils/request'
import { useUserStore } from '@/pinia-store/user'
import { mapStores } from 'pinia'
import { viewFile } from '@/utils/publicmethod.js'
export default {
  name: 'UploadFile',
  props: {
    itemIndex: {
      type: Number,
      default: 0
    },
    itemId: {
      type: String,
      required: true
    },
    title: {
      type: String,
      default: ''
    },
    value: {
      type: String,
      default: ''
    },
    ApplyDetailList: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      uploadUrl: `${COMMON_API_BASE_URL}/dist/interface/public/index.php/form/Form/upload`,
      isUploading: false,
      uploadProgress: 0,
      fileList: [],
      formats: ['docx', 'doc', 'pdf', 'jpeg', 'jpg', 'png', 'gif', 'ppt', 'pptx', 'xls', 'xlsx'],
      sizeLimit: 30, // MB
      countLimit: 5,
      nextCloud: {},
      uploadOptions: {}
    }
  },
  computed: {
    ...mapStores(useUserStore)
  },
  created () {
    this.$nextTick(() => {
      const token = uni.getStorageSync('token') || this.userStore.user.token

      this.uploadOptions = {
        url: `${COMMON_API_BASE_URL}/dist/interface/public/index.php/form/Form/upload`,
        formData: { token }
      }
    })
    this.nextCloud = uni.getStorageSync('next_cloud')
  },
  methods: {
    // 选择文件
    chooseFile () {
      const count = this.countLimit - this.fileList.length
      if (count <= 0) return uni.showToast({ title: '已达最大上传数量', icon: 'none' })
      const _self = this;
      // #ifdef APP-PLUS
      this.$refs.XeUpload.upload('file');
      // #endif
      // #ifdef H5
      uni.chooseFile({
        count,
        type: 'all',
        extension: this.formats,
        success: (res) => {
          res.tempFiles.forEach(file => {
            if (file.size > this.sizeLimit * 1024 * 1024) {
              uni.showToast({ title: `${file.name} 超过大小限制`, icon: 'none' })
              return
            }
            this.uploadFile(file)
          })
        }
      })
      // #endif
    },

    // 上传文件
    uploadFile (file) {
      this.isUploading = true
      const token = uni.getStorageSync('token') || this.userStore.user.token

      const uploadTask = uni.uploadFile({
        url: this.uploadUrl,
        filePath: file.path || file.tempFilePath,
        name: 'file',
        formData: { token },
        success: (res) => {
          try {
            const data = JSON.parse(res.data)
            if (data.status === 1) {
              const fileData = {
                ...data.data,
                name: data.data.name || file.name,
                url: this.ProcessingURL(data.data.url)
              }
              this.fileList.push(fileData)
              this.$emit('applyOrderDetailuploadEnd', {
                fileList: this.fileList,
                index: this.itemIndex
              })
            } else {
              uni.showToast({ title: '上传失败', icon: 'none' })
            }
          } catch (e) {
            uni.showToast({ title: '解析上传结果失败', icon: 'none' })
          }
        },
        fail: (err) => {
          console.error('upload error', err)
          uni.showToast({ title: '上传出错', icon: 'none' })
        },
        complete: () => {
          this.isUploading = false
          this.uploadProgress = 0
        }
      })

      // 上传进度
      uploadTask.onProgressUpdate((progress) => {
        this.uploadProgress = progress.progress
        if (progress.progress >= 100) {
          setTimeout(() => {
            this.isUploading = false
            this.uploadProgress = 0
          }, 500)
        }
      })
    },

    // 文件预览
    FileViewClick (item) {
      viewFile(item, {
        userStore: this.userStore,
        xtoken: this.nextCloud?.xtoken,
      });
    },

    // URL 处理
    ProcessingURL (url) {
      if (url.startsWith('http://117.89.250.65:81/')) {
        url = url.replace('http://117.89.250.65:81', COMMON_API_BASE_URL)
      } else if (url.startsWith('https://cloud.mfarmers.com/')) {
        url = url.replace('https://cloud.mfarmers.com', COMMON_API_BASE_URL)
      }
      return url
    },

    beforUpload (e) {
      const tempFile = {
        uuid: e.uuid,
        name: e.fileName,
        size: e.fileSize,
        status: 'uploading',
        url: '',
        progress: 0
      }
      this.fileList.push(tempFile)
      this.isUploading = true
      this.uploadProgress = 0
    },

    handleUploadCallback (e) {
      // 上传中更新进度
      if (e.type === 'onprogress' && e.data?.progress !== undefined) {
        this.uploadProgress = e.data.progress
        return
      }

      // 上传完成
      if (e.type === 'success') {
        const fileData = e.data?.[0]
        const uuid = e.data?.uuid

        const fileResponse = fileData?.response || {}
        console.log('fileResponse', fileResponse)

        // 找到对应的临时文件
        const index = this.fileList.findIndex(f => f.uuid === uuid)
        if (index === -1) return

        const fileItem = this.fileList[index]

        // 如果后端返回登录错误
        if (fileResponse?.msg === '缺少TOKEN参数') {
          uni.showToast({ title: '上传失败：未登录', icon: 'none' })
          fileItem.status = 'error'
          return
        }

        if (fileResponse.status === 1 && fileResponse.data) {
          const { id, url, name } = fileResponse.data
          fileItem.status = 'done'
          fileItem.url = this.ProcessingURL(url)
          fileItem.name = name || fileItem.name
          fileItem.id = id || ''
          fileItem.progress = 100

          this.$emit('applyOrderDetailuploadEnd', {
            fileList: this.fileList,
            index: this.itemIndex
          })

          this.isUploading = false
          this.uploadProgress = 0
        } else {
          uni.showToast({ title: '上传失败', icon: 'none' })
          fileItem.status = 'error'
        }
      }

      // 上传失败
      if (e.type === 'error') {
        uni.showToast({ title: '上传出错', icon: 'none' })
        this.isUploading = false
        this.uploadProgress = 0
      }
    },
  }
}
</script>

<style scoped>
.content {
  position: relative;
}

.upload-wrapper {
  display: flex;
  flex-direction: column;
}

.upload-btn-container {
  width: 200rpx;
}

.progress-container {
  margin-top: 20rpx;
  width: 100%;
}

.progress-bar {
  width: 100%;
  height: 8rpx;
  background-color: #e4e7ed;
  border-radius: 4rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #409eff 0%, #67c23a 100%);
  border-radius: 4rpx;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 24rpx;
  color: #606266;
  margin-top: 8rpx;
  text-align: center;
}

.file-list-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 15rpx;
  margin-top: 20rpx;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  width: 650rpx;
}

.file-name {
  flex: 1;
  color: #333;
  font-size: 28rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.delete-btn {
  color: #fff;
  background-color: #f56c6c;
  padding: 8rpx 20rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
  margin-left: 20rpx;
}
</style>
